package com.gitbl.webchat.web;


import com.gitbl.webchat.service.RoomService;
import com.gitbl.webchat.service.UserService;
import com.gitbl.webchat.utils.ArgumentsHelper;
import com.gitbl.webchat.web.control.BaseController;
import com.gitbl.webchat.web.control.RoomWSController;
import groovyjarjarcommonscli.ParseException;
import jdk.nashorn.internal.objects.annotations.Property;
import org.apache.dubbo.config.annotation.Reference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.HashSet;
import java.util.Properties;


@SpringBootApplication
@EnableAutoConfiguration
public class Application {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Reference(version = "${webchat.userService.version}",application = "${webchat.userService.name}")
    private UserService userService;
    @Reference(version = "${webchat.roomService.version}",application = "${webchat.roomService.name}")
    private RoomService roomService;

    public static void main(String[] args) throws ParseException {
        HashSet<String> systemproperties=new HashSet();
        systemproperties.add("zk");
        systemproperties.add("port");
        systemproperties.add("session.hosts");
        Properties pps = ArgumentsHelper.parseProperties(args, "use value for given property(property=value) \neg: -Dzk=192.168.10.144:2181,192.168.10.144:2082" +
                "\\\n-Dport=8083" +
                "\\\n-Dsession.hosts=127.0.0.1:6379","webchat-web-1.0-SNAPSHOT.jar" );

        if(pps==null){
            return;
        }

        for (Object p : pps.keySet()) {
            String k = p.toString();
            if(systemproperties.contains(k))
                System.setProperty(k, pps.getProperty(p.toString()));
        }

        SpringApplication.run(Application.class).close();
    }



    @Bean
    public ApplicationRunner runner() {
        BaseController.init(userService,roomService);

        return new ApplicationRunner() {
            public void run(ApplicationArguments args) throws Exception {
                roomService.ping();
                while (true)
                {
//                    WebSocketController.RTransfer c = new WebSocketController.RTransfer(new URI("ws://127.0.0.1:8081"), null);
                    //c.send("aaa");
                    // todo 可以增加一些状态检测
                    //System.out.printf("%b\n",demoService.exist("cxx"));
                    Thread.sleep(10000);
                }
            }
        };
    }
}
